package com.karst.essentials.chapter07
{
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.net.URLRequest;
	
	import org.papervision3d.lights.PointLight3D;
	import org.papervision3d.materials.BitmapMaterial;
	import org.papervision3d.materials.shadematerials.FlatShadeMaterial;
	import org.papervision3d.materials.shaders.FlatShader;
	import org.papervision3d.materials.shaders.ShadedMaterial;
	import org.papervision3d.objects.primitives.Sphere;
	import org.papervision3d.view.BasicView;
	
	internal class FlatShadingExample extends BasicView
	{
		public function FlatShadingExample()
		{
			super() ;
			createView() ;
			startRendering() ;
		}

		private var angle : Number = 0 ;
		private var light : PointLight3D = null ;
		private var colorShadMaterial : FlatShadeMaterial = null ;
		private var bmpShadMaterial : ShadedMaterial = null ;
		private var colorSphere : Sphere = null ;
		private var bmpSphere : Sphere = null ;
		private var imgLoader : Loader = null ;
		private function createView() : void
		{
			if( light == null )
			{
				light = new PointLight3D( true ) ;
			light.y = 300 ;
			light.z = 0 ;
			}
			
			if( colorShadMaterial == null )
				colorShadMaterial = new FlatShadeMaterial( light, 0xFFFFFF, 0xFF0000, 100 ) ;
			
			if( colorSphere == null )
			{
				colorSphere = new Sphere( colorShadMaterial, 240, 10, 10 ) ;
				colorSphere.x = -300 ;
			}
			
			if( imgLoader == null )
			{
				imgLoader = new Loader() ;
				imgLoader.contentLoaderInfo.addEventListener( Event.COMPLETE, loadedImgHandler ) ;
				imgLoader.load( new URLRequest( "earth.jpg" )) ;
			}
			
			scene.addChild( light ) ;
			scene.addChild( colorSphere ) ;
		}
		
		private function loadedImgHandler( event : Event ) : void
		{
			if( bmpSphere == null )
			{
				bmpShadMaterial = new ShadedMaterial( 
						new BitmapMaterial( (imgLoader.content as Bitmap).bitmapData ),
						new FlatShader( light, 0xFFFFFF, 0xFF0000, 100 ) ) ;
				bmpSphere = new Sphere( bmpShadMaterial, 240, 10, 10 ) ;
				bmpSphere.x = 300 ;
			}
			scene.addChild( bmpSphere ) ;
		}
		
		override protected function onRenderTick(event:Event=null):void
		{
			super.onRenderTick( event ) ;
			if( light )
			{
				light.y = Math.cos( angle ) * 600 ;
				light.z = Math.sin( angle ) * 400 ;
			}
			if( colorSphere )
				colorSphere.localRotationY += 2 ;
			if( bmpSphere )
				bmpSphere.localRotationY += 2 ;
			angle += .1 ;
		}
	}
}